﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml.Linq;

namespace PersonalAlbum
{
    public class RegistrationRequestsManager
    {
        private static object locker = "locker";
        private const string FileName = "RegistrationRequests.xml";
        static RegistrationRequestsManager()
        {
            if (!File.Exists(HttpContext.Current.Server.MapPath("~/App_data/" + FileName)))
            {
                File.WriteAllText(
                    HttpContext.Current.Server.MapPath("~/App_data/" + FileName),
                    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<Requests></Requests>");
            }
        }
        public static bool CheckIfExists(string email)
        {
            lock (locker)
            {
                XDocument doc = XDocument.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_data/" + FileName)));
                return doc.Descendants("Request").SingleOrDefault(e => e.Element("email").Value.Equals(email.Trim(), StringComparison.InvariantCultureIgnoreCase)) != null;
            }
        }
        public static string GenerateLink(string email, string userName)
        {
            lock (locker)
            {
                string code = Guid.NewGuid().ToString("N");
                XDocument doc = XDocument.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_data/" + FileName)));
                doc.Element("Requests").Add(new XElement("Request", new XElement("email", email.Trim()), new XElement("code", code), new XElement("userName", userName.Trim())));
                doc.Save(HttpContext.Current.Server.MapPath("~/App_data/" + FileName));
                return code;
            }
        }

        public static bool ValidateAndDelete(string code, out string userName)
        {
            lock (locker)
            {
                XDocument doc = XDocument.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_data/" + FileName)));
                var element = doc.Descendants("Request").SingleOrDefault(e => e.Element("code").Value.Equals(code.Trim(), StringComparison.InvariantCultureIgnoreCase));
                if (element != null)
                {
                    WebLogger.Trace("user found");
                    userName = element.Element("userName").Value.Trim();
                    element.Remove();
                    doc.Save(HttpContext.Current.Server.MapPath("~/App_data/" + FileName));
                    WebLogger.Trace("saved");
                    return true;
                }
                else
                {
                    WebLogger.Trace("user was not found");
                    userName = null;
                    return false;
                }
            }
        }
    }
}
